#!/usr/bin/env python
#coding:utf-8
import os
import sys
import urllib2
import urlparse
from urllister import URLLister

def getImages(addr):
    try:
        if not os.path.exists('img/'):
            os.mkdir('img')
    except:
        pass
    
    img = urllib2.urlopen(addr)
    data = img.read()
    filename = addr.split('/').pop()
    print 'Save: %s' % filename
    f = open(r'img/'+filename, 'wb')
    f.write(data)
    f.close()
    
if len(sys.argv) != 2:
    print '''
    本程序用下载指定网站上的图片，使用方法如下：
    \n\tpython urlimg.py URL
    \n\tURL 要求完整的，如：http://www.google.com
    \n'''
    sys.exit()
else:
    website = sys.argv[1]

lister = URLLister()
lister.feed(urllib2.urlopen(website).read())
for img in lister.img:
    addr = urlparse.urljoin(website, img)
    print '图片来自：%s' % addr
    getImages(addr)
